package Inventory;

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.Timer;
import Expense.ExpensePane;
import Login.Button;
import Login.DBHandler;
import Login.MainFrame;
import Sales.SalePane;
import User.UserPane;
import Inventory.GBPane;

public class InventoryPane extends JPanel implements ItemListener,
		ActionListener, MouseMotionListener, MouseListener, FocusListener,
		KeyListener {
	private JPanel parent;
	private DBHandler db;
	private CardLayout cards;
	private BufferedImage bg, panel1, panel2;
	private JFrame frame;
	private Button salesBtn, inBtn, expBtn, usBtn, logBtn, viewIn, manageIn;
	// private Button prevDay, prevRow, nextDay, nextRow;
	private Timer time;
	private int userType, curPanel;
	private String error;
	private JLabel day, month, year, row;
	private JComboBox dayBox, yearBox, monthBox;
	private JTextField rowBox;
	private Date date;
	private JLabel d, m, y;
	private JButton prevDay, prevRow, nextDay, nextRow;
	private JPanel viewPane;
	private ArrayList<InventoryRecord> supplies;
	private ArrayList<JLabel> supplyNames;
	private ArrayList<JLabel> balances;
	private ArrayList<JTextField> inBoxes, outBoxes;
	private JScrollPane scrollPane;
	private int batchMark;

	public InventoryPane(DBHandler db, JPanel parent, CardLayout cards,
			BufferedImage bg, JFrame frame, int userType) {
		curPanel = 0;
		this.setLayout(null);
		this.db = db;
		this.parent = parent;
		this.cards = cards;
		this.bg = bg;
		this.frame = frame;
		this.userType = userType;
		showButtons();
		error = "";
		date = new Date();
		supplies = getDBInventoryItems();

		viewIn.setCurImg(1);

		day = new JLabel("Day :");
		month = new JLabel("Month :");
		year = new JLabel("Year :");
		row = new JLabel("Row :");
		d = new JLabel((date.getDate() + 1) + "");

		prevDay = new JButton("Previous Day");
		prevRow = new JButton("Previous Row");
		nextDay = new JButton("Next Day");
		nextRow = new JButton("Next Row");

		
		String s = "";
		switch (date.getMonth()) {
		case 0:
			s = "January";
			break;
		case 1:
			s = "February";
			break;
		case 2:
			s = "March";
			break;
		case 3:
			s = "April";
			break;
		case 4:
			s = "May";
			break;
		case 5:
			s = "June";
			break;
		case 6:
			s = "July";
			break;
		case 7:
			s = "August";
			break;
		case 8:
			s = "September";
			break;
		case 9:
			s = "October";
			break;
		case 10:
			s = "November";
			break;
		case 11:
			s = "December";
			break;
		}
		m = new JLabel(s);
		y = new JLabel((date.getYear() + 1900) + "");

		dayBox = new JComboBox();
		monthBox = new JComboBox();
		yearBox = new JComboBox();
		rowBox = new JTextField();
		viewPane = new JPanel();// ung ky nick

		dayBox.setBounds(280, 185, 45, dayBox.getPreferredSize().height);
		monthBox.setBounds(375, 185, 100, monthBox.getPreferredSize().height);
		yearBox.setBounds(523, 185, 70, yearBox.getPreferredSize().height);
		day.setBounds(248, 169, 50, 50);
		month.setBounds(335, 169, 70, 50);
		year.setBounds(475, 169, 70, 50);
		row.setBounds(335, 225, 50, 25);
		rowBox.setBounds(380, 227, 90, 26);
		d.setBounds(298, 187, 50, d.getPreferredSize().height);
		m.setBounds(385, 187, 100, m.getPreferredSize().height);
		y.setBounds(523, 187, 50, y.getPreferredSize().height);
		prevDay.setBounds(135, 180, prevDay.getPreferredSize().width,
				prevDay.getPreferredSize().height);
		prevRow.setBounds(205, 225, prevRow.getPreferredSize().width,
				prevRow.getPreferredSize().height);
		nextDay.setBounds(615, 180, nextDay.getPreferredSize().width,
				nextDay.getPreferredSize().height);
		nextRow.setBounds(510, 225, nextRow.getPreferredSize().width,
				nextRow.getPreferredSize().height);
		// viewPane.setBounds(137, 270, 554, 200);

		Font font2 = new Font("Calibri", Font.PLAIN, 15);
		dayBox.setFont(font2);
		monthBox.setFont(font2);
		yearBox.setFont(font2);
		d.setFont(font2);
		m.setFont(font2);
		y.setFont(font2);

		this.add(dayBox);
		this.add(day);
		this.add(monthBox);
		this.add(month);
		this.add(yearBox);
		this.add(year);
		this.add(row);
		this.add(rowBox);
		this.add(prevDay);
		this.add(prevRow);
		this.add(nextDay);
		this.add(nextRow);

		setInComponents(true);
		recordPaneConfig();
		scrollPane = new JScrollPane(viewPane);
		scrollPane.setBounds(137, 270, 554, 200);
		try {
			setComboBoxItems(monthBox);
			setComboBoxItems(yearBox);
		} catch (SQLException SqlEx) {
		}

		// this.add(viewPane);//ung ky nick
		this.add(d);
		this.add(m);
		this.add(y);
		this.add(scrollPane);

		this.addMouseListener(this);
		this.addMouseMotionListener(this);

		time = new Timer(300, this);

		prevDay.addActionListener(this);
		nextDay.addActionListener(this);
		prevRow.addActionListener(this);
		nextRow.addActionListener(this);
		rowBox.addFocusListener(this);

		dayBox.addItemListener(this);
		monthBox.addItemListener(this);
		yearBox.addItemListener(this);
		rowBox.addKeyListener(this);
		this.setBoxesEditable(false);
	}
	public ArrayList<InventoryRecord> getDBInventoryItems(){
		ArrayList<InventoryRecord> Records=new ArrayList<InventoryRecord>();
		ResultSet RS;
		int ctr=0;
		
		RS=db.MySQLSelect("SELECT InventoryID,InventoryIn,InventoryOut,TimeRecorded, unit, productname from Inventory,Product where TimeRecorded=Date(now()) AND prCode=ProductCode;");
		
		try {
			
			while(RS.next()){
				Records.add(new InventoryRecord(RS.getString(1), RS.getString(5),RS.getString(6), RS.getDate(4), RS.getInt(2),RS.getInt(3)));
				ctr++;
			}
			if(ctr==0)
				return initializeDailyRecord(1);
			RS.close();
		} catch (SQLException SQLe) {
			// TODO Auto-generated catch block
			error="*Error "+SQLe;
		}
		
		return Records;
	}
	public ArrayList<InventoryRecord> getDBInventoryItems(String s){
		ArrayList<InventoryRecord> Records=new ArrayList<InventoryRecord>();
		ResultSet RS;
		
		/*"SELECT productName,InventoryIn,InventoryOut from Inventory,Product where prCode=ProductCode AND TimeRecorded='"+
		yearBox.getSelectedItem()+"-"+monthBox.getSelectedItem()+"-"+dayBox.getSelectedItem()+"';"*/
		
		RS=db.MySQLSelect("SELECT InventoryID,InventoryIn,InventoryOut,TimeRecorded, unit, productname from Inventory,Product where TimeRecorded=Date('"+s+"') AND prCode=ProductCode;");
		
		try {
			while(RS.next()){
				Records.add(new InventoryRecord(RS.getString(1), RS.getString(5),RS.getString(6), RS.getDate(4), RS.getInt(2),RS.getInt(3)));
			}
			
			RS.close();
		} catch (SQLException SQLe) {
			// TODO Auto-generated catch block
			error="*Error: Error in Collecting Records";
		}
		
		
		return Records;
	}

	public void recordPaneConfig(){
		viewPane.removeAll();
		//supplies=getDBinventoryItems();

		if(supplies.size()>0){
			viewPane.setLayout(new GridLayout(supplies.size()+1, 4));
		
			viewPane.add(new JLabel("Product"));
			viewPane.add(new JLabel("In"));
			viewPane.add(new JLabel("Out"));
			viewPane.add(new JLabel("Balance"));
		
			supplyNames=new ArrayList<JLabel>();
			inBoxes=new ArrayList<JTextField>();
			outBoxes=new ArrayList<JTextField>();
			balances=new ArrayList<JLabel>();
		
			for(int ctr=0;ctr<supplies.size();ctr++){
				supplyNames.add(new JLabel(supplies.get(ctr).getUnitName()+" "+supplies.get(ctr).getSupplyName()));
				viewPane.add(supplyNames.get(ctr));
				inBoxes.add(new JTextField(supplies.get(ctr).getIn()+""));
				outBoxes.add(new JTextField(supplies.get(ctr).getOut()+""));
				balances.add(new JLabel(""+supplies.get(ctr).getBalance()));
				viewPane.add(inBoxes.get(ctr));
				viewPane.add(outBoxes.get(ctr));
				viewPane.add(balances.get(ctr));
			
				balanceCheck(ctr);
			
				inBoxes.get(ctr).setEditable(false);
				outBoxes.get(ctr).setEditable(false);
				inBoxes.get(ctr).addFocusListener(this);
				outBoxes.get(ctr).addFocusListener(this);
				inBoxes.get(ctr).addKeyListener(this);
				outBoxes.get(ctr).addKeyListener(this);
			}
		}
		else {
			//Statuslbl.setFont(DayLbl.getFont());
			//Statuslbl.setText("No Record for this Day");
			viewPane.add(new JLabel("<html><h2>No Record on this day</h2></html>"));
		}
		batchMark=supplies.size();
		rowBox.setText(supplies.size()+"");
	}

	private void recordPaneConfig(int rows){
		int ctr;
		viewPane.removeAll();
		//supplies=getDBinventoryItems();


		viewPane.setLayout(new GridLayout(rows+1, 4));
		
		viewPane.add(new JLabel("Product"));
		viewPane.add(new JLabel("In"));
		viewPane.add(new JLabel("Out"));
		viewPane.add(new JLabel("Balance"));
		
		supplyNames=new ArrayList<JLabel>();
		inBoxes=new ArrayList<JTextField>();
		outBoxes=new ArrayList<JTextField>();
		balances=new ArrayList<JLabel>();
		
		for(ctr=0;ctr<supplies.size();ctr++){
			supplyNames.add(new JLabel(supplies.get(ctr).getUnitName()+" "+supplies.get(ctr).getSupplyName()));
			inBoxes.add(new JTextField(supplies.get(ctr).getIn()+""));
			outBoxes.add(new JTextField(supplies.get(ctr).getOut()+""));
			balances.add(new JLabel(""+supplies.get(ctr).getBalance()));
			
		}
		
		for(ctr=0;ctr<rows;ctr++){
			viewPane.add(supplyNames.get(ctr));
			viewPane.add(inBoxes.get(ctr));
			viewPane.add(outBoxes.get(ctr));
			viewPane.add(balances.get(ctr));
			
			if(curPanel==0){
				inBoxes.get(ctr).setEditable(false);
				outBoxes.get(ctr).setEditable(false);
			}
			else{
				inBoxes.get(ctr).setEditable(true);
				outBoxes.get(ctr).setEditable(true);
			}
			
			inBoxes.get(ctr).addFocusListener(this);
			outBoxes.get(ctr).addFocusListener(this);
			balanceCheck(ctr);
			
			inBoxes.get(ctr).setEditable(false);
			outBoxes.get(ctr).setEditable(false);
			inBoxes.get(ctr).addFocusListener(this);
			outBoxes.get(ctr).addFocusListener(this);
			inBoxes.get(ctr).addKeyListener(this);
			outBoxes.get(ctr).addKeyListener(this);
		}
		batchMark=ctr;
	}
	

	private void infoBatches(boolean next){
		int rows=Integer.valueOf(rowBox.getText()),i=0;
		if(next&&rows<supplies.size()){
			while(batchMark>=0&&batchMark+rows>supplies.size())
				batchMark--; 
			if(batchMark+rows<=supplies.size()){
				for(int ctr=batchMark;ctr<rows+batchMark;ctr++){
					supplyNames.get(i).setIcon(null);
					supplyNames.get(i).setText(supplies.get(ctr).getUnitName()+" "+supplies.get(ctr).getSupplyName());
					inBoxes.get(i).setText(supplies.get(ctr).getIn()+"");
					outBoxes.get(i).setText(supplies.get(ctr).getOut()+"");
					balances.get(i).setText(supplies.get(ctr).getBalance()+"");
					i++;
				}
				batchMark+=rows;

			}  
		}
		else if(rows<supplies.size()){
			batchMark-=rows;
			while(batchMark-rows<0)
				batchMark++;
			if(batchMark-rows>=0){
				int ctr;
				i=rows;
				for(ctr=batchMark;ctr>=batchMark-rows;ctr--){
					supplyNames.get(i).setIcon(null);
					supplyNames.get(i).setText(supplies.get(ctr).getUnitName()+" "+supplies.get(ctr).getSupplyName());
					inBoxes.get(i).setText(supplies.get(ctr).getIn()+"");
					outBoxes.get(i).setText(supplies.get(ctr).getOut()+"");
					balances.get(i).setText(supplies.get(ctr).getBalance()+"");
					i--;
				}
				//batchMark+=rows; 
			}
			
		}
	}
	
	
	public void balanceCheck(int index) {
		ImageIcon exclamation;
		exclamation = new ImageIcon("Images/exclaim.png");
		if (supplies.get(index).getBalance() < 15)
			supplyNames.get(index).setIcon(exclamation);
		else
			supplyNames.get(index).setIcon(null);
	}

	public void setComboBoxItems(JComboBox cb) throws SQLException{
		cb.removeAllItems();
		if(cb==monthBox){
			cb.addItem("January");cb.addItem("Febuary");cb.addItem("March");
			cb.addItem("April");cb.addItem("May");cb.addItem("June");
			cb.addItem("July");cb.addItem("August");cb.addItem("September");
			cb.addItem("October");cb.addItem("November");cb.addItem("December");
			
			ResultSet RS=db.MySQLSelect("Select Month(now());"),RY,RD;
			RS.first();
			cb.setSelectedIndex(RS.getInt(1)-1);
		
			RY=db.MySQLSelect("Select Year(now());");
			RY.first();
			
			int limit,ctr;
			
			if(RS.getInt(1)==1||RS.getInt(1)==3||RS.getInt(1)==5||RS.getInt(1)==7||RS.getInt(1)==8
					||RS.getInt(1)==10||RS.getInt(1)==12)
				limit=31;
			else if(RS.getInt(1)==2)
				if(RY.getInt(1)%4!=0)
					limit =28;
				else limit=29;
			else limit=30;
			
			for(ctr=1;ctr<=limit;ctr++)
				dayBox.addItem(""+ctr);
			RS.close();
			RY.close();
			
			
			RD=db.MySQLSelect("Select Day(now());");
			RD.first();
			
			dayBox.setSelectedItem(RD.getString(1));
			RD.close();
			
			}
		else if(cb==yearBox){
			ResultSet RS=db.MySQLSelect("Select Year(TimeRecorded) from Inventory group by year(TimeRecorded);");
			
			while(RS.next())
				cb.addItem(RS.getString(1));
			cb.setSelectedIndex(cb.getItemCount()-1);
			RS.close();
		}
		else if(cb==dayBox){
			ResultSet RS=db.MySQLSelect("Select Month(now());"),RY,RD;
			RS.first();
			monthBox.setSelectedIndex(RS.getInt(1)-1);
			
			RY=db.MySQLSelect("Select Year(now());");
			RY.first();
			
			int limit,ctr;
			
			if(RS.getInt(1)==1||RS.getInt(1)==3||RS.getInt(1)==5||RS.getInt(1)==7||RS.getInt(1)==8
					||RS.getInt(1)==10||RS.getInt(1)==12)
				limit=31;
			else if(RS.getInt(1)==2)
				if(RY.getInt(1)%4!=0)
					limit =28;
				else limit=29;
			else limit=30;
			
			for(ctr=1;ctr<=limit;ctr++)
				dayBox.addItem(""+ctr);
			RS.close();
			RY.close();
			
			
			RD=db.MySQLSelect("Select Day(now());");
			RD.first();
			
			dayBox.setSelectedItem(RD.getString(1));
			RD.close();
		}
	}
	private ArrayList<InventoryRecord> initializeDailyRecord(int i) throws SQLException{
		ArrayList<InventoryRecord> Records=new ArrayList<InventoryRecord>();
		ResultSet RS,RT;
		int ctr=0;
		
		RS=db.MySQLSelect("SELECT InventoryID,InventoryIn,InventoryOut, unit, productname,prCode from Inventory,Product where TimeRecorded=Date_SUB(CurDate(),INTERVAL "+i+" Day)AND prCode=ProductCode;");
		RT=db.MySQLSelect("SELECT curDate();");
		RT.first();
		while(RS.next()){
			Records.add(new InventoryRecord(RT.getString(1)+ctr, RS.getString(4), RS.getString(5), RT.getDate(1), RS.getInt(2)-RS.getInt(3), 0));
			db.MySQLInsert("Insert INTO INventory values ('"+(RT.getString(1)+ctr)
					+"',"+(RS.getInt(2)-RS.getInt(3))+",0,now(),'"+RS.getString(6)+"');");
			ctr++;
			
		}
		
		if(ctr==0)
			return initializeDailyRecord(i+1);
		
		RT.close();
		RS.close();
		 return Records;
	}
	

	public void rowChange(int rows) {

		error = "";
		if (rows > supplies.size()) {
			rows = supplies.size();
			error = "*Error: Rows exceed number of records";
		}
		if (rows < 0) {
			rows = 0;
			error = "*Error: Must have at least 0 row";
		}
		rowBox.setText("" + rows);
		recordPaneConfig(rows);
		paintAnsestors(viewPane);

	}

	//method that changes the dayBox based on the month
	public void dayBoxConfig(int month){
		int limit,year=Integer.valueOf(yearBox.getSelectedItem().toString()),Day=dayBox.getItemCount();
		//Determine month to determine number of days
		if(month==0||month==2||month==4||month==6||month==7||month==9||month==11)
			limit =31;
		else if(month==1)
			if(year%4!=0)
				limit =28;
			else limit=29;
		else limit=30;
		
		dayBox.removeItemListener(this);
		//dayBox.setSelectedIndex(0);
		
		if(Day<limit)
			for(int ctr=Day+1;ctr<=limit;ctr++)
				dayBox.addItem(""+ctr);
		else if(Day>limit){
			dayBox.removeAllItems();
			for(int ctr=1;ctr<=limit;ctr++)
				dayBox.addItem(""+ctr);
		}
		monthBox.addItemListener(this);
		dayBox.addItemListener(this);
	}

	// Method that responds to the next and previous day buttons
	//Method that responds to the next and previous day buttons
	public void nextPrevDay(int change){
		int month;
		if(change>0){
			if(dayBox.getSelectedIndex()<dayBox.getItemCount()-change)
				dayBox.setSelectedIndex(dayBox.getSelectedIndex()+change);
			else if(monthBox.getSelectedIndex()<monthBox.getItemCount()-change){
				monthBox.removeItemListener(this);
				monthBox.setSelectedIndex(monthBox.getSelectedIndex()+change);
				month=monthBox.getSelectedIndex();
				
				dayBoxConfig(month);
				dayBox.setSelectedIndex(0);
			}
			else{
				yearBox.removeItemListener(this);
				yearBox.addItem(""+(Integer.valueOf(yearBox.getSelectedItem().toString())+1));
				yearBox.setSelectedIndex(yearBox.getItemCount()-1);
				monthBox.setSelectedIndex(0);
				dayBox.setSelectedIndex(0);
				yearBox.addItemListener(this);
				
			}
			
		}
		else if(change<0){
			if(dayBox.getSelectedIndex()>0)
				dayBox.setSelectedIndex(dayBox.getSelectedIndex()+change);
			else if(monthBox.getSelectedIndex()>0){
				monthBox.removeItemListener(this);
				monthBox.setSelectedIndex(monthBox.getSelectedIndex()+change);
				month=monthBox.getSelectedIndex();
				dayBoxConfig(month);
				
				dayBox.setSelectedIndex(dayBox.getItemCount()-1);
			}
			else if(yearBox.getSelectedIndex()>0)
				yearBox.setSelectedIndex(yearBox.getSelectedIndex()+change);
			else error="*Error: No more record in the previous Years";
		}
	}



	public void showButtons() {
		try {
			switch (userType) {
			case 4:
				salesBtn = new Button("images/b1.png", "images/b1a.png",
						"images/b1.png");
				usBtn = new Button("images/b5.png", "images/b5a.png",
						"images/b5.png");

			case 3:
				inBtn = new Button("images/b2a.png", "images/b2.png",
						"images/b2.png");
				expBtn = new Button("images/b3.png", "images/b3a.png",
						"images/b3.png");
				logBtn = new Button("images/b7.png", "images/b7a.png",
						"images/b7.png");
				viewIn = new Button("images/i2.png", "images/i2a.png",
						"images/i2.png");
				manageIn = new Button("images/i3.png", "images/i3a.png",
						"images/i3.png");
			}
			panel1 = ImageIO.read(new File("images/viewin.png"));
			panel2 = ImageIO.read(new File("images/manageIn.png"));
			/*
			 * prevDay = new Button("images/prev.png", "images/preva.png",
			 * "images/prev.png"); prevRow = new Button("images/prevrow.png",
			 * "images/prevrowa.png", "images/prevrow.png"); nextDay = new
			 * Button("images/nextday.png", "images/nextdaya.png",
			 * "images/nextday.png"); nextRow = new Button("images/nextrow.png",
			 * "images/nextrowb.png", "images/nextrow.png");
			 */
			// panel3= ImageIO.read(new File("images/removeuser.png"));

		} catch (IOException e) {
			System.out.print("Image not found");
			e.printStackTrace();
		}

	}
	public void setBoxesEditable(boolean b){
		for (int ctr = 0; ctr < supplies.size(); ctr++) {
			inBoxes.get(ctr).setEditable(b);
			outBoxes.get(ctr).setEditable(b);
		}
	}
	@Override
	public void actionPerformed(ActionEvent AE) {
		// TODO Auto-generated method stub
		repaint();
		scrollPane.revalidate();
		switch (curPanel) {

		case 0:
			viewIn.setCurImg(1);
			setBoxesEditable(false);
			break;
		case 1:
			manageIn.setCurImg(1);
			setBoxesEditable(true);
		}

		if (AE.getSource() == nextDay)
			nextPrevDay(1);
		
		else if (AE.getSource() == prevDay)
			nextPrevDay(-1);
		else if (AE.getSource() == nextRow)
			infoBatches(true);
		else if (AE.getSource() == prevRow)
			infoBatches(false);
		scrollPane.revalidate();
	}

	public void paintAnsestors(Container cn) {
		Container C = cn;
		while (C.getParent() != null) {
			C.repaint();
			C = C.getParent();
		}
	}

	public void paint(Graphics g) {
		super.paint(g);
		Graphics2D g2D = (Graphics2D) g;
		time.start();
		g2D.drawImage(bg, 0, 0, null);
		switch (userType) {
		case 4:
			g2D.drawImage(usBtn.getCurImg(), 497, 8, null);
			g2D.drawImage(salesBtn.getCurImg(), 145, 8, null);
			g2D.drawImage(inBtn.getCurImg(), 269, 8, null);
			g2D.drawImage(expBtn.getCurImg(), 383, 8, null);
			break;
		case 3:
			g2D.drawImage(inBtn.getCurImg(), 138, 8, null);
			g2D.drawImage(expBtn.getCurImg(), 243, 8, null);
		}
		g2D.drawImage(logBtn.getCurImg(), 611, 8, null);
		g2D.drawImage(viewIn.getCurImg(), 10, 168, null);
		g2D.drawImage(manageIn.getCurImg(), 10, 306, null);
		Font font = new Font("Calibri", Font.PLAIN, 20);

		g2D.setColor(Color.RED);
		g2D.setFont(font);

		if (curPanel == 0) {
			g2D.drawImage(panel1, 125, 105, null);
			/*
			 * g2D.drawImage(prevDay.getCurImg(), 135, 175, null);
			 * g2D.drawImage(prevRow.getCurImg(), 205, 225, null);
			 * g2D.drawImage(nextDay.getCurImg(), 615, 175, null);
			 * g2D.drawImage(nextRow.getCurImg(), 545, 225, null);
			 */
			g2D.drawString(error, 297, 167);

		}
		if (curPanel == 1) {
			/*
			 * g2D.drawImage(prevRow.getCurImg(), 205, 225, null);
			 * g2D.drawImage(nextRow.getCurImg(), 545, 225, null);
			 */
			g2D.drawImage(panel2, 125, 105, null);
			g2D.drawString(error, 297, 167);

		}
	}

	public void setInComponents(boolean b) {

		dayBox.setVisible(b);
		monthBox.setVisible(b);
		yearBox.setVisible(b);
		d.setVisible(!b);
		m.setVisible(!b);
		y.setVisible(!b);

		prevDay.setVisible(b);
		nextDay.setVisible(b);
	}

	@Override
	public void mouseClicked(MouseEvent m) {
		// TODO Auto-generated method stub

		switch (userType) {
		case 4:
			if (m.getX() >= 151 && m.getX() <= 229 && m.getY() >= 8
					&& m.getY() <= 86)// within the boundaries of sales btn
				cards.show(parent, "sales");
			else if (m.getX() >= 390 && m.getX() <= 469 && m.getY() >= 8
					&& m.getY() <= 86)// within the boundaries of exp btn
				cards.show(parent, "expense");
			else if (m.getX() >= 504 && m.getX() <= 581 && m.getY() >= 7
					&& m.getY() <= 85)// within the boundaries of us btn
				cards.show(parent, "users");
			break;
		case 3:
			if (m.getX() >= 249 && m.getX() <= 327 && m.getY() >= 7
					&& m.getY() <= 86)// within the boundaries of exp btn
				cards.show(parent, "expense");

			break;
		}

		if (m.getX() >= 17 && m.getX() <= 95 && m.getY() >= 170
				&& m.getY() <= 246) {// within the boundaries of view btn
			error  = "";
			viewIn.setCurImg(1);
			manageIn.setCurImg(0);
			curPanel = 0;
			setInComponents(true);
			setBoxesEditable(false);
		}
		if (m.getX() >= 16 && m.getX() <= 97 && m.getY() >= 305
				&& m.getY() <= 386) {// within the boundaries of manage btn
			error  = "";
			viewIn.setCurImg(0);
			manageIn.setCurImg(1);
			curPanel = 1;
			setInComponents(false);
			supplies = getDBInventoryItems();
			recordPaneConfig();
			setBoxesEditable(true);
			scrollPane.revalidate();
		}
	
		if (m.getX() >= 617 && m.getX() <= 698 && m.getY() >= 9
				&& m.getY() <= 85) {// within the boundaries of log out btn
			final JFrame frame2  = new JFrame("Confirm Action");

    		JLabel label  = new JLabel();
    		JLabel label2 = new JLabel("Are you sure you want to log out?");
    		JButton yes = new JButton("Yes");
    		JButton no = new JButton("No");
    		yes.addActionListener(
    				new ActionListener(){
    					@Override
    					public void actionPerformed(ActionEvent arg0) {
    						// TODO Auto-generated method stub
    						new MainFrame();
    						frame.dispose();
    		                frame2.dispose();
    					}
    				}
    		);
    		yes.setIcon(new ImageIcon("Images/yes.png"));
    		no.setIcon(new ImageIcon("Images/no.png"));
    		
    		no.addActionListener(
    				new ActionListener(){
    					@Override
    					public void actionPerformed(ActionEvent arg0) {
    						// TODO Auto-generated method stub
    						frame2.dispose();
    					}
    				}
    		);
    		
    		label2.setFont(new Font(Font.SERIF, Font.PLAIN, 17));
    		
    		JPanel panel  = new JPanel();
    		ImageIcon confirm;
    		confirm= new ImageIcon("Images/confirmaction.png");
    		label.setIcon(confirm);
    		
    		panel.add(label);
    		panel.add(label2);
    		panel.add(yes);
    		panel.add(no);

    		label.setBounds(26, 20, 120, 120);
    		label2.setBounds(145, 40, 250, 30);
    		yes.setBounds(160, 105, 80, yes.getPreferredSize().height);
    		no.setBounds(260, 105, 80, no.getPreferredSize().height+2);
    		
    		panel.setLayout(null);
    		frame2.add(panel);
    		frame2.setVisible(true);
    		frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    		frame2.setSize(400, 200);
    		frame2.setLocationRelativeTo(null);
    	 	
    	}	   
        	
	}

	@Override
	public void mouseEntered(MouseEvent m) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseExited(MouseEvent m) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mousePressed(MouseEvent m) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseReleased(MouseEvent m) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseDragged(MouseEvent m) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseMoved(MouseEvent m) {
		// TODO Auto-generated method stub
		switch (userType) {

		case 4:
			if (m.getX() >= 151 && m.getX() <= 229 && m.getY() >= 8
					&& m.getY() <= 86)// within the boundaries of sales btn
				salesBtn.setCurImg(1);
			else if (m.getX() >= 390 && m.getX() <= 469 && m.getY() >= 8
					&& m.getY() <= 86)// within the boundaries of exp btn
				expBtn.setCurImg(1);
			else if (m.getX() >= 504 && m.getX() <= 581 && m.getY() >= 7
					&& m.getY() <= 85)// within the boundaries of us btn
				usBtn.setCurImg(1);
			else if (m.getX() >= 617 && m.getX() <= 698 && m.getY() >= 9
					&& m.getY() <= 85)// within the boundaries of log out btn
				logBtn.setCurImg(1);

			else {
				salesBtn.setCurImg(0);
				inBtn.setCurImg(0);
				expBtn.setCurImg(0);
				usBtn.setCurImg(0);
				logBtn.setCurImg(0);
			}
			break;
		case 3:
			if (m.getX() >= 249 && m.getX() <= 327 && m.getY() >= 7
					&& m.getY() <= 86)// within the boundaries of exp btn
				expBtn.setCurImg(1);
			else if (m.getX() >= 617 && m.getX() <= 698 && m.getY() >= 9
					&& m.getY() <= 85)// within the boundaries of log out btn
				logBtn.setCurImg(1);
			else {
				inBtn.setCurImg(0);
				expBtn.setCurImg(0);
				logBtn.setCurImg(0);
			}
			break;
		}

		if (m.getX() >= 17 && m.getX() <= 95 && m.getY() >= 170
				&& m.getY() <= 246)// within the boundaries of view btn
			viewIn.setCurImg(1);
		else if (m.getX() >= 16 && m.getX() <= 97 && m.getY() >= 305
				&& m.getY() <= 386)// within the boundaries of manage btn
			manageIn.setCurImg(1);
		/*
		 * else if (m.getX() >= 134&&
		 * m.getX()<=228&&m.getY()>=177&&m.getY()<=206)//within the boundaries
		 * of prev btn prevDay.setCurImg(1); else if (m.getX() >= 614&&
		 * m.getX()<=703&&m.getY()>=177&&m.getY()<=206)//within the boundaries
		 * of next btn nextDay.setCurImg(1); else if (m.getX() >= 205&&
		 * m.getX()<=296&&m.getY()>=226&&m.getY()<=253)//within the boundaries
		 * of prevrow btn prevRow.setCurImg(1); else if (m.getX() >= 546&&
		 * m.getX()<=636&&m.getY()>=226&&m.getY()<=253)//within the boundaries
		 * of nextrow btn nextRow.setCurImg(1);
		 */
		else {

			viewIn.setCurImg(0);
			manageIn.setCurImg(0);
			/*
			 * prevDay.setCurImg(0); nextDay.setCurImg(0); prevRow.setCurImg(0);
			 * nextRow.setCurImg(0);
			 */

		}

	}

	@Override
	public void itemStateChanged(ItemEvent IE) {
		// getDBinventoryItems();
		if (IE.getSource() == monthBox) {
			monthBox.removeItemListener(this);// Remove recursion since
												// itemstateChanged can be
												// trigerred in this method
			dayBoxConfig(monthBox.getSelectedIndex());
		}
		if (IE.getSource() == dayBox || IE.getSource() == monthBox
				|| IE.getSource() == yearBox) {
			supplies = getDBInventoryItems(yearBox.getSelectedItem().toString()
					+ "-" + (monthBox.getSelectedIndex() + 1) + "-"
					+ dayBox.getSelectedItem().toString());

			recordPaneConfig();
			// RecordPane.repaint();
			paintAnsestors(viewPane);
		}
	}

	@Override
	public void focusGained(FocusEvent FE) {

	}
	public void focusLost(FocusEvent FE) {
		int i;
		error="";
			if(inBoxes.contains(FE.getSource())){
				i=inBoxes.indexOf(FE.getSource());
				
				try{
					if(Integer.valueOf(inBoxes.get(i).getText())>=0)
					db.MySQLUpdate("UPDATE Inventory SET InventoryIn='"+inBoxes.get(i).getText()+"' where InventoryID='"
						+supplies.get(i).getID()+"';");
					else inBoxes.get(i).setText(supplies.get(i).getIn()+"");
						supplies.get(i).setIn(Integer.valueOf(inBoxes.get(i).getText()));
						balances.get(i).setText(supplies.get(i).getBalance()+"");
					balanceCheck(i);
					}catch(Exception general){
						inBoxes.get(i).setText(supplies.get(i).getIn()+"");
						error="*Error: Not a number";
					}
				
		}
			else if(outBoxes.contains(FE.getSource())){
				i=outBoxes.indexOf(FE.getSource());
				try{
					if(Integer.valueOf(outBoxes.get(i).getText()) <=Integer.valueOf(inBoxes.get(i).getText())&&Integer.valueOf(outBoxes.get(i).getText())>=0){
					db.MySQLUpdate("UPDATE Inventory SET InventoryOut='"+outBoxes.get(i).getText()+"' where InventoryID='"
						+supplies.get(i).getID()+"';");
					supplies.get(i).setOut(Integer.valueOf(outBoxes.get(i).getText()));
					balances.get(i).setText(supplies.get(i).getBalance()+"");
					balanceCheck(i);
					}
					else{
						if(Integer.valueOf(outBoxes.get(i).getText()) >Integer.valueOf(inBoxes.get(i).getText()))
							error="*Error: Out can not be more than In";
						else error="*Error: No negative values";
						outBoxes.get(i).setText(supplies.get(i).getOut()+"");
					}
				}catch(Exception general){
					outBoxes.get(i).setText(supplies.get(i).getOut()+"");
					error="*Error: Not a number";
				}
				
				paintAnsestors(viewPane);
		}
			else if(FE.getSource()==rowBox){
				try{
					rowChange(Integer.valueOf(rowBox.getText()));
				}catch(NumberFormatException NF){
					error="*Error: Please enter a valid number";
				}
			}
	
	}

	@Override
	public void keyPressed(KeyEvent KE) {
		
	}

	@Override
	public void keyReleased(KeyEvent KE) {
		// TODO Auto-generated method stub
		
		int i;
		
		if(KE.getKeyCode()==KeyEvent.VK_QUOTE)
			error="*Error: Invalid Input";
		else error="";
		
		if(KE.getSource()==rowBox&&KE.getKeyCode()==KeyEvent.VK_ENTER){
			try{
				rowChange(Integer.valueOf(rowBox.getText()));
				//rowBox.getParent().requestFocus();
			}catch(NumberFormatException NF){

				error="*Error: Please enter a valid number";
			}
			paintAnsestors(viewPane);
		}
		else if(inBoxes.contains(KE.getSource())&&KE.getKeyCode()==KeyEvent.VK_ENTER){
			i=inBoxes.indexOf(KE.getSource());
			outBoxes.get(i).requestFocus();
		}
		else if(outBoxes.contains(KE.getSource())&&KE.getKeyCode()==KeyEvent.VK_ENTER){
			i=outBoxes.indexOf(KE.getSource());
			if(i<inBoxes.size()-1)
				inBoxes.get(i+1).requestFocus();
		}
	}

	@Override
	public void keyTyped(KeyEvent KE) {
		// TODO Auto-generated method stub
		
	}
}
